﻿using Gx.Common;
using Gx.Common.Core;
using Gx.Dal;
using Gx.Dal.Manage;
using Gx.Dal.Shared;
using Gx.Model;
using Gx.Model.Entity;
using Gx.Model.Enums;
using Gx.Model.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;


namespace Gx.Bll.Manage
{
    public class LKTransferBll
    {

        protected LKTransferDal dal = new LKTransferDal();
        protected BaseDal<LKTransferDetail> detailDal = new BaseDal<LKTransferDetail>();
        protected BaseDal<LKTransferCost> costDal = new BaseDal<LKTransferCost>();

        protected LKAttachmentBll attachmentBll = new LKAttachmentBll();

        /// <summary>
        /// 分页列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public PagedList<LKTransfer> GetLKTransferPageList(LKTransferInput input)
        {
            return dal.GetLKTransferPageList(input);
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public List<LKTransfer> GetLKTransfers()
        {
            return dal.GetAll().ToList();
        }

        /// <summary>
        /// 新增商品转卡单
        /// </summary>
        /// <param name="lKTransfer"></param>
        /// <returns></returns>
        public ReturnModel AddLKTransfer(LKTransferDto lKTransfer)
        {

            string maxCode = dal.GetMaxLKTransferCode();
            string code = "Z" + DateTime.Now.ToString("yyMMdd") + "001";
            if (!string.IsNullOrWhiteSpace(maxCode))
            {
                var maxMonth = maxCode.Substring(2, 2);
                var nowMonth = DateTime.Now.ToString("MM");
                if (maxMonth == nowMonth)
                {
                    int num = Convert.ToInt32(maxCode);
                    num++;
                    code = "Z" + num.ToString();//DateTime.Now.ToString("yyMMdd") + num.ToString().PadLeft(3, '0');
                }
            }

            lKTransfer.Transfer.TransferNo = code;

            lKTransfer.Transfer.CreateTime = DateTime.Now;
            lKTransfer.Transfer.CreateUserId = LoginHelper.GetUserId();
            lKTransfer.Transfer.CreateUser = LoginHelper.UserName();
            lKTransfer.Transfer.CompanyId = UserContext.CompanyId;
            var result = dal.AddLKTransfer(lKTransfer);//dal.Insert(lKTransfer);


            var transfer = lKTransfer.Transfer;
            var costs = lKTransfer.Costs;
            var details = lKTransfer.Details;
            LKWarehouseEntryDto lKWarehouseEntryDto = new LKWarehouseEntryDto
            {
                WarehouseEntry = new LKWarehouseEntry
                {
                    BillNo = transfer.TransferNo,
                    EntryTime = DateTime.Now,
                    CustomerId = transfer.InCustomerId,
                    CustomerNo = transfer.InCustomerNo,
                    CustomerName = transfer.InCustomerName,
                    CompanyId = transfer.CompanyId,
                    ContractNo = transfer.ContractNo,
                    RentalWarehouseType = transfer.RentalWarehouseType,
                    ChargingUnit = transfer.ChargingUnit,
                    ColdAlgorithm = transfer.ColdAlgorithm,
                    Cycle = transfer.Cycle,
                    ColdUnitPrice = transfer.ColdUnitPrice,
                    TotalTon = transfer.TotalTon,
                    Total = transfer.Total,
                    Amount = transfer.InAmount,
                    Tonnage = transfer.Tonnage,
                    IsByTon = transfer.IsByTon,
                    CreateUserId = transfer.CreateUserId,
                    CreateTime = transfer.CreateTime,
                    ModifyUserId = transfer.ModifyUserId,
                    ModifyTime = transfer.ModifyTime,
                    Remark = transfer.Remark,
                    BillSource=$"商品转卡单{code}"
                },
                Details = details.Select(s => new LKWarehouseEntryDetail
                {
                    GoodsNo = s.NewGoodsNo,
                    GoodsId = s.GoodsId,
                    GoodsSpecId = s.GoodsSpecId,
                    WareHouseId = s.InHouse,
                    GoodsName = s.GoodsName,
                    GoodsSpecName = s.GoodsSpecName,
                    WareHouseName = s.InHouseName,
                    Weight = s.Weight,
                    Number = s.TransferNumber,
                    Area = s.Area,
                    TonWeight = s.TonWeight,
                    Remark1 = s.Remark1,
                    Remark2 = s.Remark2,
                    Remark3 = s.Remark3
                }).ToList(),
                Costs = costs.Where(c=>c.TransferType==2).Select(s => new LKWarehouseEntryCost
                {
                    CostId = s.CostId,
                    UnitPrice = s.UnitPrice,
                    Unit = s.Unit,
                    UnitName = s.UnitName,
                    Number = s.Number,
                    Amount = s.Amount,
                }).ToList()
            };

            LKWarehouseEntryBll lKWarehouseEntryBll = new LKWarehouseEntryBll();
            lKWarehouseEntryBll.AddLKWarehouseEntry(lKWarehouseEntryDto);

            LKWarehouseOutBll lKWarehouseOutBll = new LKWarehouseOutBll();
            LKWarehouseOutDto lKWarehouseOutDto = new LKWarehouseOutDto
            {
                WarehouseOut = new LKWarehouseOut
                {
                    OutTime = DateTime.Now,
                    CustomerId = transfer.OutCustomerId,
                    CustomerNo = transfer.OutCustomerNo,
                    CustomerName = transfer.OutCustomerName,
                    CompanyId = transfer.CompanyId,
                    TotalTon = transfer.TotalTon,
                    Total = transfer.Total,
                    Amount = transfer.OutAmout,
                    IsByTon = transfer.IsByTon,
                    CreateUserId = transfer.CreateUserId,
                    CreateTime = transfer.CreateTime,
                    ModifyUserId = transfer.ModifyUserId,
                    ModifyTime = transfer.ModifyTime,
                    Remark = transfer.Remark,
                    BillSource = $"商品转卡单{code}"
                },
                Details = details.Select(s => new LKWarehouseOutDetail
                {
                    GoodsNo=s.NewGoodsNo,
                    GoodsId = s.GoodsId,
                    GoodsSpecId = s.GoodsSpecId,
                    WareHouseId = s.OutHouse,
                    GoodsName = s.GoodsName,
                    GoodsSpecName = s.GoodsSpecName,
                    WareHouseName = s.OutHouseName,
                    Weight = s.Weight,
                    OutNumber = s.InventoryNumber,
                    Area = s.InventoryArea,
                    TonWeight = s.InventoryTonWeight,
                    Remark1 = s.Remark1,
                    Remark2 = s.Remark2,
                    Remark3 = s.Remark3
                }).ToList(),
                Costs = costs.Where(c => c.TransferType == 1).Select(s => new LKWarehouseOutCost
                {
                    CostId = s.CostId,
                    UnitPrice = s.UnitPrice,
                    Unit = s.Unit,
                    UnitName = s.UnitName,
                    Number = s.Number,
                    Amount = s.Amount,
                }).ToList()
            };
            lKWarehouseOutBll.AddLKWarehouseOut(lKWarehouseOutDto);

            if (result && lKTransfer.AttachmentId > 0)
            {
                attachmentBll.SaveLKAttachment(new LKAttachment
                {
                    Id = lKTransfer.AttachmentId,
                    BillNo = code,
                    BillType = (int)BillTypeTemplate.WarehouseTransfer,
                });
            }
            return new ReturnModel { Success = result, Msg = result ? "新增成功" : "新增失败" };
        }

        /// <summary>
        /// 编辑商品转卡单
        /// </summary>
        /// <param name="lKTransferDto"></param>
        /// <returns></returns>
        public bool EditLKTransfer(LKTransferDto lKTransferDto)
        {
            var lKTransfer = lKTransferDto.Transfer;
            var cus = dal.Get(lKTransfer.Id);
            if (cus == null)
            {
                return false;
            }
            if (cus.CompanyId != UserContext.CompanyId) return false;

            lKTransfer.CreateTime = cus.CreateTime;
            lKTransfer.CreateUserId = cus.CreateUserId;
            lKTransfer.CreateUser = cus.CreateUser;
            lKTransfer.ModifyUserId = LoginHelper.GetUserId();
            lKTransfer.ModifyUser = LoginHelper.UserName();
            lKTransfer.ModifyTime = DateTime.Now;
            lKTransfer.CompanyId = UserContext.CompanyId;
            var result= dal.EditLKTransfer(lKTransferDto);//dal.Update(lKTransfer);
            if (result && lKTransferDto.AttachmentId > 0)
            {
                attachmentBll.DeleteLKAttachment(lKTransferDto.Transfer.TransferNo);
                attachmentBll.SaveLKAttachment(new LKAttachment
                {
                    Id = lKTransferDto.AttachmentId,
                    BillNo = lKTransferDto.Transfer.TransferNo,
                    BillType = (int)BillTypeTemplate.WarehouseTransfer,
                });
            }
            return result;
        }

        /// <summary>
        /// 删除商品转卡单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteLKTransfer(int id)
        {
            return dal.DeleteLKTransfer(id);//DeleteById(id);
        }

        /// <summary>
        /// 获取商品转卡单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public LKTransferDto GetLKTransferById(int id)
        {
            var bill = dal.Get(id);

            if (bill.CompanyId != UserContext.CompanyId)
                return new LKTransferDto();

            var detailList = detailDal.GetListByWhere("TransferId=@id", new { id }).ToList();
            var costList = costDal.GetListByWhere("TransferId=@id", new { id }).ToList();

            var attachment = attachmentBll.GetLKAttachmentView(bill.TransferNo);
            return new LKTransferDto { Transfer = bill, Details = detailList, Costs = costList, FilePath = attachment?.AttachmentName, FileName = attachment?.OriginalName };
        }
    }
}

